package com.bocai.freeman.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by kaizen on 15/11/29.
 */
public enum BitmapPhotoUtils {
    INSTANCE;

    public static String compress(String filePath, Context context) {
        FileOutputStream outputStream = null;
        Bitmap bitmap;
        File parent = FileUtil.getInstance(context).makeDir("pic");
        String path = parent.getPath() + File.separator
                + "picture" + System.currentTimeMillis() + ".jpg";

        //  String path = App.getInstance().getCacheDir().getAbsolutePath() + "/" + System.currentTimeMillis() + ".jpg";
        //  L.e(path);
        try {
            outputStream = new FileOutputStream(path);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(filePath, options);
            options.inJustDecodeBounds = false;
            options.inSampleSize = caculateInSampleSize(options, 800, 800);
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            bitmap = BitmapFactory.decodeFile(filePath, options);
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 50, outputStream)) {
                return path;
            } else {
                return filePath;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return filePath;
    }

    public static int caculateInSampleSize(BitmapFactory.Options options, int reqWidth,
                                    int reqHeight) {
        int width = options.outWidth;
        int height = options.outHeight;

        int inSampleSize = 1;

        if (width > reqWidth || height > reqHeight) {
            int widthRadio = Math.round(width * 1.0f / reqWidth);
            int heightRadio = Math.round(height * 1.0f / reqHeight);

            inSampleSize = Math.max(widthRadio, heightRadio);
        }

        return inSampleSize;
    }
}
